<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class WxBase
{
    private $AppId;
    private $Secret;
    private $GrantType;
    private $AuthUrl;

    public function __construct()
    {
        $this->AppId = IOSS_StaticConfig::$AppId;
        $this->Secret = IOSS_StaticConfig::$Secret;
        $this->GrantType = IOSS_StaticConfig::$GrantType;
        $this->AuthUrl = IOSS_StaticConfig::$AuthUrl;
    }

    /**
     * @param $url
     * @param array $params
     * @param int $expire
     * @param array $extend
     * @param string $hostIp
     * @return array
     * curl请求
     */
    function makeRequest($url, $params = array(), $expire = 0, $extend = array(), $hostIp = '')
    {
        if (empty($url)) {
            return array('code' => '100');
        }

        $_curl = curl_init();
        $_header = array(
            'Accept-Language: zh-CN',
            'Connection: Keep-Alive',
            'Cache-Control: no-cache'
        );

        if (!empty($hostIp)) {
            $urlInfo = parse_url($url);
            if (empty($urlInfo['host'])) {
                $urlInfo['host'] = substr(DOMAIN, 7, -1);
                $url = "http://{$hostIp}{$url}";
            } else {
                $url = str_replace($urlInfo['host'], $hostIp, $url);
            }
            $_header[] = "Host: {$urlInfo['host']}";
        }

        if (!empty($params)) {
            curl_setopt($_curl, CURLOPT_POSTFIELDS, http_build_query($params));
            curl_setopt($_curl, CURLOPT_POST, true);
        }

        if (substr($url, 0, 8) == 'https://') {
            curl_setopt($_curl, CURLOPT_SSL_VERIFYPEER, FALSE);
            curl_setopt($_curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        }
        curl_setopt($_curl, CURLOPT_URL, $url);
        curl_setopt($_curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($_curl, CURLOPT_USERAGENT, 'API PHP CURL');
        curl_setopt($_curl, CURLOPT_HTTPHEADER, $_header);

        if ($expire > 0) {
            curl_setopt($_curl, CURLOPT_TIMEOUT, $expire); // 处理超时时间
            curl_setopt($_curl, CURLOPT_CONNECTTIMEOUT, $expire); // 建立连接超时时间
        }

        // 额外的配置
        if (!empty($extend)) {
            curl_setopt_array($_curl, $extend);
        }

        $result['result'] = curl_exec($_curl);
        $result['code'] = curl_getinfo($_curl, CURLINFO_HTTP_CODE);
        $result['info'] = curl_getinfo($_curl);
        if ($result['result'] === false) {
            $result['result'] = curl_error($_curl);
            $result['code'] = -curl_errno($_curl);
        }

        curl_close($_curl);
        return $result;
    }

    /**
     * 微信登录
     */
    public function login($code){
        //获取小程序信息
        $params = [
            'appid' => $this->AppId,
            'secret' => $this->Secret,
            'js_code' => $code,
            'grant_type' => $this->GrantType
        ];

        //获取用户的openID以及会话秘钥
        $res = $this->makeRequest($this->AuthUrl, $params);
        if ($res['code'] !== 200 || !isset($res['result'])) {
            return false;
        }
        $res_data    = json_decode($res['result'], true);
        return $res_data;
    }

    public function generate_user_token($user_id, $days){
        $db = IOSS_DB::getInstance();
        $currentTime    = time();
        $expireTime     = $currentTime + 24 * 3600 * $days;
        $token          = md5(uniqid()) . md5(uniqid());
        $insert =[
            'token'       => $token,
            'user_id'     => $user_id,
            'expire_time' => $expireTime,
            'create_time' => $currentTime,
            'update_time' => $currentTime
        ];
        $exist = $db->select('*')
            ->from('user_token')
            ->where('user_id',$user_id)
            ->get()
            ->row();
        if ($exist){
            $db->update('user_token',['token' => $token, 'expire_time' => $expireTime ],['user_id' => $user_id]);
        }else{
            $db->insert('user_token',$insert);
        }
        return ['token' => $token, 'expire_time' => $expireTime ];
    }

    /**
     * 请求微信二维码
     * @param $url
     * @param $data
     * @param bool $ssl
     * @return bool|mixed
     */
    public function _requestPost($url, $data, $ssl=true) {
        //curl完成
        $curl = curl_init();
        //设置curl选项
        curl_setopt($curl, CURLOPT_URL, $url);//URL
        $user_agent = isset($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '  
    Mozilla/5.0 (Windows NT 6.1; WOW64; rv:38.0) Gecko/20100101 Firefox/38.0 FirePHP/0.7.4';
        curl_setopt($curl, CURLOPT_USERAGENT, $user_agent);//user_agent，请求代理信息
        curl_setopt($curl, CURLOPT_AUTOREFERER, true);//referer头，请求来源
        curl_setopt($curl, CURLOPT_TIMEOUT, 30);//设置超时时间
        //SSL相关
        if ($ssl) {
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);//禁用后cURL将终止从服务端进行验证
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2);//检查服务器SSL证书中是否存在一个公用名(common name)。
        }
        // 处理post相关选项
        curl_setopt($curl, CURLOPT_POST, true);// 是否为POST请求
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);// 处理请求数据
        // 处理响应结果
        curl_setopt($curl, CURLOPT_HEADER, false);//是否处理响应头
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);//curl_exec()是否返回响应结果

        // 发出请求
        $response = curl_exec($curl);
        if (false === $response) {
            echo '<br>', curl_error($curl), '<br>';
            return false;
        }
        curl_close($curl);
        return $response;
    }
}
